<?php
	/**
	* Get Request list
	* return in Json format
	* @author trungdt
	* @since Nov 6, 2011
	*/
	if (!defined('EXPONENT')) exit('');
	
	if (!exponent_users_isLoggedIn())
		die();
	
	global $user;
	$sql_where=" (user_id = {$user->id}) ";
	if (exponent_users_isAdmin() || 
	exponent_permissions_check(array("edit","delete","administrate", "approve", "add_calendar"),$loc))
	{
		$sql_where=" 1 ";
	}
	
	$sort="";
	if (isset($_REQUEST['sort']))
	{
		$sort=$_REQUEST['sort'];
		if (isset($_REQUEST['order']) && ($_REQUEST['order'] != "asc"))
			$sortOrder = "DESC";
		$sort = " ORDER BY {$sort} {$sortOrder}";
	}
	else
		$sort="ORDER BY request_date DESC, approve";
	

	// get page
	$page=1;
	if (isset($_REQUEST['page']))
		$page=intval($_REQUEST['page']);
	$pageSize=10;
	if (isset($_REQUEST['pageSize']))
		$pageSize=intval($_REQUEST['pageSize']);
	$start=($page-1)*$pageSize;

	$sql="SELECT {$db->prefix}requestmodule_request.*, {$db->prefix}user.username, {$db->prefix}user.firstname, {$db->prefix}user.lastname 
	FROM {$db->prefix}requestmodule_request LEFT JOIN {$db->prefix}user
	ON {$db->prefix}requestmodule_request.user_id = {$db->prefix}user.id
	WHERE {$sql_where}
	{$sort}
	LIMIT {$start},{$pageSize}
	";
	$data=$db->selectObjectsBySql($sql);

	foreach ($data as $k=>$v) {
		// 
		$v->userfullname=trim("{$v->firstname} {$v->lastname}");
		$v->request_date=date("d/m/Y H:i:s", $v->request_date);
		$v->from_date=date("d/m/Y H:i:s", $v->from_date);
		$v->approve_bk=$v->approve;
		if ($v->approve ==0 )
			$v->approve_date="";
		else
			$v->approve_date=date("d/m/Y H:i:s", $v->approve_date);
		if ($v->cancel_request == 0 )
			$v->cancel_request="";
		else
			$v->cancel_request=date("d/m/Y H:i:s", $v->cancel_request);
	}

	// prepare for return json
	$ret=null;
	$ret->total=count($data);
	$ret->rows=$data;
	echo json_encode($ret);
?>